package com.example.controller.webchat;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dao.BusinessUserDao;
import com.example.dto.BusinessUserDTO;
import com.example.dto.SysUserDTO;
import com.example.dto.webchat.WebchatUserInfoDTO;
import com.example.dto.webchat.WebchatUserInfoParamDTO;
import com.example.entity.BusinessUserEntity;
import com.example.model.api.Result;
import com.example.utils.ConvertUtils;
import com.example.utils.JsonUtils;
import com.example.utils.WXDecryptUtil;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("webchat")
@Slf4j
public class WebchatController {

    @Autowired
    private BusinessUserDao businessUserDao;

    @Operation(summary = "微信小程序用户信息", description = "微信小程序用户信息")
    @PostMapping("userinfo")
    public Result<WebchatUserInfoDTO> userinfo(@RequestBody WebchatUserInfoParamDTO webchatUserInfoParamDTO){
        try {
            String userinfostr = WXDecryptUtil.decryptData(webchatUserInfoParamDTO.getEncryptedData(), webchatUserInfoParamDTO.getIv(), webchatUserInfoParamDTO.getSessionKey());

            log.info("{}", userinfostr);

            String openid = webchatUserInfoParamDTO.getOpenid();

            WebchatUserInfoDTO webchatUserInfoDTO = JsonUtils.parseObject(userinfostr, WebchatUserInfoDTO.class);
            BusinessUserDTO businessUserDTO = new BusinessUserDTO();
            businessUserDTO.setOpenid(openid);
            businessUserDTO.setAvatarUrl(webchatUserInfoDTO.getAvatarUrl());
            businessUserDTO.setRealName(webchatUserInfoDTO.getNickName());
            businessUserDTO.setGender(webchatUserInfoDTO.getGender());
            BusinessUserEntity businessUserEntity = ConvertUtils.sourceToTarget(businessUserDTO, BusinessUserEntity.class);
            LambdaQueryWrapper<BusinessUserEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BusinessUserEntity::getOpenid, openid);
            businessUserDao.update(businessUserEntity, queryWrapper);
            webchatUserInfoDTO.setOpenid(openid);
            return new Result<WebchatUserInfoDTO>().ok(webchatUserInfoDTO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
